<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>查询历史天气</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.17.1/xlsx.full.min.js"></script>
</head>
<body>
<div>
    <label for="excel-file" class="file-upload-label">查询历史天气</label>
    <input type="file" id="excel-file" accept=".xlsx, .xls" onchange="handleFileUpload()"/>
    <br><br>
</div>

<div id="result"></div>

<script>
    function formatDate(date) {
        let year = date.getFullYear();
        let month = (date.getMonth() + 1).toString().padStart(2, '0');
        let day = date.getDate().toString().padStart(2, '0');
        let hours = date.getHours().toString().padStart(2, '0');
        let minutes = date.getMinutes().toString().padStart(2, '0');
        let seconds = date.getSeconds().toString().padStart(2, '0');
        return `${year}${month}${day}${hours}${minutes}${seconds}`;
    }

    async function handleFileUpload() {
        const fileInput = document.getElementById('excel-file');
        const file = fileInput.files[0];

        if (!file) {
            alert('请先选择一个 Excel 文件');
            return;
        }

        // 创建一个 FormData 对象，用于发送包含文件的请求
        const formData = new FormData();
        formData.append('file', file);

        try {
            const response = await fetch('http://47.93.37.107:8080/weather/api/queryHistory/file', {
                method: 'POST',
                headers: {
                    'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
                    'Accept': '*/*',
                },
                body: formData,
            });


            if (response.ok) {
                // 处理返回的 Excel 文件
                const contentDisposition = response.headers.get('Content-Disposition');
                const filename = contentDisposition && contentDisposition.match(/filename="(.+)"/) ? contentDisposition.match(/filename="(.+)"/)[1] : '查询历史天气' + formatDate(new Date()) + '.xlsx';
                // 获取响应流作为 Blob 对象
                const blob = await response.blob();
                // 创建下载链接并触发下载
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = filename;  // 设置文件下载的默认名称
                a.click();

                // 释放 Blob URL
                window.URL.revokeObjectURL(url);
            } else {
            }
        } catch (error) {
        } finally {
            // 清除文件输入控件的值
            fileInput.value = '';
        }
    }
</script>
</body>
</html>
